<template>
  <div>
    <!-- 导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容区 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showadddialog">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom',i1===0?'bdtop':'bdbottom','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removerightByid(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2===0?'':'bdtop','vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 通过for循环嵌套渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removerightByid(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removerightByid(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showeditdialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleterole(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限窗口 -->
    <el-dialog
      title="分配权限"
      @close="setRightdialogclosed"
      :visible.sync="setRightdialogVisible"
      width="50%"
    >
      <el-tree
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色表单 -->
    <el-dialog title="编辑角色" :visible.sync="editdialogVisible" width="50%" @close="editrolesclosed">
      <el-form
        label-width="100px"
        class="demo-ruleForm"
        :model="editroleForm"
        :rules="editrules"
        ref="editRoleRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editroleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editroleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitroleForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑添加角色菜单 -->
    <el-dialog title="添加角色" :visible.sync="adddialogVisible" width="50%" @close="addrolesclosed">
      <el-form
        label-width="100px"
        class="demo-ruleForm"
        :model="addroleForm"
        :rules="addrules"
        ref="addRoleRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addroleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addroleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitaddForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //角色列表数据
      rolesList: [],
      //所有权限列表数据
      rightsList: [],
      //控制分配权限
      setRightdialogVisible: false,
      // 树形控件属性绑定对象
      treeProps: {
        children: "children",
        label: "authName",
      },
      // 默认选中节点id值数组
      defkeys: [116],
      // 分配角色权限的id
      roleid: "",
      // 展示编辑角色的对话框
      editdialogVisible: false,
      // 编辑角色列表数据
      editroleForm: {
        roleName: "",
        roleDesc: "",
      },
      // 角色编辑规则
      editrules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
      },
      // 编辑角色id
      editroleid: "",
      // 展示添加角色的对话框
      adddialogVisible: false,
      // 添加角色列表数据
      addroleForm: {
        roleName: "",
        roleDesc: "",
      },
      // 添加角色规则
      addrules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getroleslist();
  },
  methods: {
    //获取角色列表
    async getroleslist() {
      const { data: res } = await this.$axios.get("roles");
      if (res.meta.status != 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolesList = res.data;
    },
    // 根据id删除对应权限
    async removerightByid(role, rightid) {
      //弹框提示
      const result = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result !== "confirm") {
        return this.$message.info("取消了删除！");
      }

      const { data: res } = await this.$axios.delete(
        `roles/${role.id}/rights/${rightid}`
      );
      if (res.meta.status != 200) {
        return this.$message.error("删除权限失败！");
      }
      this.$message.success("删除权限成功！");
      role.children = res.data;
    },
    //展示分配对话框
    async showSetRightDialog(role) {
      this.roleid = role.id;
      // 获取所有权限数据
      const { data: res } = await this.$axios.get("rights/tree");
      if (res.meta.status != 200) {
        return this.$message.error("获取权限数据失败");
      }
      this.rightsList = res.data;

      // 获取三级节点
      this.getkeys(role, this.defkeys);
      this.setRightdialogVisible = true;
    },
    //获取三级权限id
    getkeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getkeys(item, arr));
    },
    //监听关闭权限对话框
    setRightdialogclosed() {
      this.defkeys = [];
    },
    //为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      const { data: res } = await this.$axios.post(
        `roles/${this.roleid}/rights`,
        {
          rids: idStr,
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功");
      this.getroleslist();
      this.setRightdialogVisible = false;
    },
    // 删除角色
    async deleterole(id) {
      const result = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result !== "confirm") {
        return this.$message.info("取消了删除！");
      }
      const { data: res } = await this.$axios.delete(`roles/${id}`);
      if (res.meta.status != 200) {
        return this.$message.error("删除角色失败！");
      }
      this.$message.success("删除角色成功！");
      this.getroleslist();
    },
    // 展示编辑角色对话框
    showeditdialog(id) {
      this.editroleid = id;
      this.editdialogVisible = !this.editdialogVisible;
      this.rolesList.forEach((item) => {
        if (item.id == this.editroleid) {
          this.editroleForm = item;
        }
      });
    },
    //监听编辑角色对话框的关闭
    editrolesclosed() {
      this.$refs.editRoleRef.resetFields();
    },
    // 提交编辑角色数据
    async submitroleForm() {
      this.$refs.editRoleRef.validate(async (valid) => {
        if (valid) {
          // 发起请求
          const { data: res } = await this.$axios.put(
            "roles/" + this.editroleid,
            {
              roleName: this.editroleForm.roleName,
              roleDesc: this.editroleForm.roleDesc,
            }
          );
          if (res.meta.status !== 200)
            return this.$message.error("角色修改失败");
          this.$message.success("角色修改成功");
          //编辑角色用户框关闭
          this.editdialogVisible = false;
          this.getroleslist();
        } else {
          return false;
        }
      });
    },
    // 展示添加角色对话框
    showadddialog() {
      this.adddialogVisible = !this.adddialogVisible;
    },
    //监听添加角色对话框的关闭
    addrolesclosed() {
      this.$refs.addRoleRef.resetFields();
    },
    // 提交添加角色请求
    async submitaddForm() {
      this.$refs.addRoleRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$axios.post("roles",this.addroleForm);
          if (res.meta.status != 201) {
            return this.$message.error("角色添加失败");
          }
          this.$message.success("角色添加失败");
          this.adddialogVisible = false;
          this.getroleslist();
        } else {
         
          return false;
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>